const formatTime = (date) => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = (n) => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

/**
 * 16进制字符串转ArrayBuffer
 */
const hexString2ArrayBuffer = function (hexStr) {
	var count = hexStr.length / 2
	let buffer = new ArrayBuffer(count)
	let dataView = new DataView(buffer)
	for (var i = 0; i < count; i++) {
		var curCharCode = parseInt(hexStr.substr(i * 2, 2), 16)
		dataView.setUint8(i, curCharCode)
	}
	return buffer
}

/**
 * ArrayBuffer转16进制字符串
 */
const arrayBuffer2HexString = function (buf) {
	var out = ''
	var u8a = new Uint8Array(buf)
	var single
	for (var i = 0; i < u8a.length; i++) {
		single = u8a[i].toString(16)
		while (single.length < 2) single = '0'.concat(single)
		out += single
	}
	return out
}

//蓝牙匹配规则
const get_bt_address = function (btaddress) {
	var localArray = ['', ':', '', ':', '', ':', '', ':', '', ':', '']
	var blueidLength = localArray.length
	for (var i = 0; i < blueidLength; i++) {
		if (!localArray[i]) {
			localArray[i] = btaddress.substring(i, i + 2)
		}
	}
	return localArray.join('')
}

const sleep = (numberMillis) => {
	var now = new Date()
	var exitTime = now.getTime() + numberMillis
	while (true) {
		now = new Date()
		if (now.getTime() > exitTime) return
	}
}

const isPoneAvailable = (str) => {
	var myreg = /^[1][3,4,5,6,7,8][0-9]{9}$/
	if (!myreg.test(str)) {
		return false
	} else {
		return true
	}
}

const showStatusTips = (title, content, type = 'toast') => {
	if (type == 'toast') {
		wx.showToast({
			title,
			icon: 'none'
		})
		return
	}
}

module.exports = {
	hexString2ArrayBuffer,
	arrayBuffer2HexString,
	sleep,
	isPoneAvailable,
	get_bt_address,
	showStatusTips
}
